package cn.kgc.controller;

import cn.kgc.pojo.Blog;
import cn.kgc.pojo.User;
import cn.kgc.service.BlogService;
import cn.kgc.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * 项目名：project0926
 * 创建人：君忆zm
 * 创建时间：2019/10/18-15:42
 */
@Controller
@RequestMapping("blog")
public class BlogController {
    @Resource
    BlogService blogService;
    @Resource
    UserService userService;

    public BlogService getBlogService() {
        return blogService;
    }

    public void setBlogService(BlogService blogService) {
        this.blogService = blogService;
    }

    @RequestMapping("query.action")
    public String queryBlog(@RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize,
                            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                            @RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageIndex,
                            Model model, HttpSession session) {
        System.out.println("开始查询");
        PageHelper.startPage(pageIndex, pageSize);
        User user = (User) session.getAttribute("user");
        List<Blog> blogList = blogService.blogList(user.getId());
        List<User> userList = userService.userList();
        PageInfo<Blog> pageInfo = new PageInfo<>(blogList);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("userList", userList);
        return "bloglist";
    }

    @RequestMapping("/add.action")
    public String add(@ModelAttribute("blog") Blog blog) {
        return "blogadd";
    }

    @RequestMapping(value = "add.action", method = RequestMethod.POST)
    public String insertBlog(Blog blog, HttpServletRequest request) {
        blog.setPublishtime(new Date());
        blog.setUserid(((User) request.getSession().getAttribute("user")).getId());
        if (blogService.insertBlog(blog) > 0) {
            return "redirect:/blog/query.action";
        } else {
            return "redirect:/blog/add.action";
        }
    }

    @RequestMapping("delete.action")
    public String deleteBlog(@RequestParam(value = "id") Integer id, HttpServletRequest request) {
        if (blogService.deleteBlog(id) > 0) {
            request.setAttribute("deleteMessage", "删除成功");
        } else {
            request.setAttribute("deleteMessage", "删除失败");
        }
        return "redirect:/blog/query.action";
    }

}
